package io.renren.wechat.service.contact;

import io.renren.wechat.service.contact.dto.OpenIdResponse;
import io.renren.wechat.service.contact.dto.UserLoginInfoResponse;
import io.renren.wechat.service.suite.SuiteService;
import io.renren.wechat.service.suite.dto.AdminInfo;
import io.renren.wechat.support.ResponseEntityUtils;
import io.renren.wechat.support.WechatConstants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dmcp@qq.com
 * @since 2021/11/26 23:11
 */
@Component
public class UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);
    /* 1=管理员用户；2=普通用户 */
    public static final int ADMIN_USER_TYPE = 1;
    public static final int NORMAL_USER_TYPE = 2;
    public static final int NONE_USER_TYPE = -1;

    private SuiteService suiteService;
    private RestTemplate fastRestTemplate;

    public boolean isAdminUser(String corpId, String userId, String agentId, String state, String suiteToken) {
        String visitingAgentId = agentId;
        if (StringUtils.isBlank(visitingAgentId)) {
            visitingAgentId = suiteService.getVisitingAgentIdFromCache(corpId, userId, suiteToken);
        }
        if (StringUtils.isBlank(visitingAgentId)) {
            throw new RuntimeException("agentId is required");
        }

        LOGGER.debug("current visitingAgentId: {}, userId={}, corpId={}", visitingAgentId, userId, corpId);

        final List<AdminInfo> adminList = suiteService.getAdminList(corpId, visitingAgentId, state);

        LOGGER.debug("got with corpId: {}, adminList: {}", corpId, adminList);

        if (CollectionUtils.isEmpty(adminList)) {
            return false;
        }

        for (AdminInfo adminInfo : adminList) {
            if (adminInfo.getUserId().equals(userId)) {
                return true;
            }
        }

        return false;
    }

    /**
     * https://work.weixin.qq.com/api/doc/90001/90143/90338
     *
     * @param corpId corp id
     * @param userId userId
     * @return user openId
     */
    public String userId2openId(String corpId, String userId, String state) {
        LOGGER.info("userId2openId, state = {}", state);
        state = state.replace(",", "");
        final String corpAccessToken = suiteService.getAuthCorpAccessToken(corpId, Integer.valueOf(state));

        Map<String, String> params = new HashMap<>();
        params.put("userid", userId);

        LOGGER.debug("userId2openId params, corpAccessToken: {}, params: {}", corpAccessToken, params);

        String url = String.format(WechatConstants.SUITE_USERID_TO_OPENID_URL, corpAccessToken);

        final ResponseEntity<OpenIdResponse> responseEntity = fastRestTemplate.postForEntity(url, params, OpenIdResponse.class);

        LOGGER.debug("userId2openId response entity: {}", responseEntity);

        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("调用获取应用的管理员列表[userId2openId]请求执行失败");
        }

        final OpenIdResponse response = responseEntity.getBody();
        if (response == null) {
            LOGGER.warn("obtain userId2openId failed, response body is empty!");
            throw new RuntimeException("获取 userId2openId 失败，响应为空");
        }

        boolean isError = ResponseEntityUtils.isError(responseEntity) || response.isError();
        if (isError) {
            LOGGER.warn(">>>>>>>obtain userId2openId failed, errMsg: {}", response.getErrmsg());
            throw new RuntimeException("获取 userId2openId 失败");
        }

        return response.getOpenId();
    }

    /**
     * 获取登录用户信息
     * https://open.work.weixin.qq.com/api/doc/90001/90143/91125
     *
     * @param corpId   corpId
     * @param authCode auth code
     * @return userLogin info
     */
    public UserLoginInfoResponse getUserLoginInfo(String corpId, String authCode, String state) {
        final String corpAccessToken = suiteService.getAuthCorpAccessToken(corpId, Integer.valueOf(state));

        Map<String, String> params = new HashMap<>();
        params.put("auth_code", authCode);

        LOGGER.debug("getUserLoginInfo params, corpAccessToken: {}, params: {}", corpAccessToken, params);

        String url = String.format(WechatConstants.SUITE_GET_USER_LOGIN_INFO_URL, corpAccessToken);

        final ResponseEntity<UserLoginInfoResponse> responseEntity = fastRestTemplate.postForEntity(url, params, UserLoginInfoResponse.class);

        LOGGER.debug("getUserLoginInfo response entity: {}", responseEntity);

        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("调用获取应用的管理员列表[getUserLoginInfo]请求执行失败");
        }

        final UserLoginInfoResponse response = responseEntity.getBody();
        if (response == null) {
            LOGGER.warn("obtain getUserLoginInfo failed, response body is empty!");
            throw new RuntimeException("获取 getUserLoginInfo 失败，响应为空");
        }

        boolean isError = ResponseEntityUtils.isError(responseEntity) || response.isError();
        if (isError) {
            LOGGER.warn(">>>>>>>obtain getUserLoginInfo failed, errMsg: {}", response.getErrmsg());
            throw new RuntimeException("获取 getUserLoginInfo 失败");
        }

        return response;
    }


    @Autowired
    public void setFastRestTemplate(RestTemplate fastRestTemplate) {
        this.fastRestTemplate = fastRestTemplate;
    }

    @Autowired
    public void setSuiteService(SuiteService suiteService) {
        this.suiteService = suiteService;
    }
}
